package com.qf.drbackend.server.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.drbackend.mapper.AddressBookMapper;
import com.qf.drbackend.pojos.AddressBook;
import com.qf.drbackend.pojos.R;
import com.qf.drbackend.server.AddressBookService;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
public class AddressBookServiceImpl extends ServiceImpl<AddressBookMapper, AddressBook> implements AddressBookService {

    @Transactional
    @Override
    public R setDefaultAddr(AddressBook addressBook) {
        Object uid = SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        //将原来默认地址修改为非默认地址
        Wrapper<AddressBook> qw = Wrappers.lambdaUpdate(AddressBook.class)
                .set(AddressBook::getIsDefault,0)
                .set(AddressBook::getUpdateUser,uid)
                .set(AddressBook::getUpdateTime,new Date())
                .eq(AddressBook::getUserId,uid)
                .eq(AddressBook::getIsDefault,1);
        update(qw);

        //设置新的默认地址
        addressBook.setIsDefault(1);
        addressBook.setUpdateTime(new Date());
        addressBook.setUpdateUser(Long.parseLong(uid.toString()));

        updateById(addressBook);

        return R.success("更新默认地址成功");
    }
}
